﻿using System;
using System.Collections.Generic;
using System.Text;
using ExpressionUtil.Node.Common;
using ExpressionUtil.Common;
using ExpressionUtil.Parser;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace ExpressionUtil.Node
{
    /// <summary>
    /// 平均值运算节点（支持可变参数）
    /// </summary>
    [Serializable]
    internal class AvgFunctionNode : Common.FunctionNode, ISerializable
    {
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public AvgFunctionNode()
            : base()
        {
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="info">要填充数据的 System.Runtime.Serialization.SerializationInfo</param>
        /// <param name="context">此序列化的目标</param>
        public AvgFunctionNode(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// 执行节点运算
        /// </summary>
        /// <param name="context">执行参数</param>
        /// <returns>执行结果的类型</returns>
        public override ExecuteRunTimeType Execute(ExecuteContext context)
        {
            decimal sum = 0;
            for (int i = 0; i < this.Parameters.Count; i++)
            {
                ExecuteRunTimeType type = this.Parameters[i].Execute(context);
                CheckHelper.IsDecimalType(type, "Avg function parameter must be decimal type.");
                sum += context.GlobalTempNum;
            }
            context.GlobalTempNum = sum / this.Parameters.Count;
            return ExecuteRunTimeType.Decimal;
        }

        /// <summary>
        /// 创建树节点
        /// </summary>
        /// <param name="context">解析参数</param>
        public static void CreateAvgFunctionNode(ParseContext context)
        {
            int parameterCount = context.FunctionParameterCount.Peek();
            System.Diagnostics.Debug.Assert(parameterCount > 0, "Invalidate parameter count.");
            if (parameterCount <= 0 || context.PostfixStack.Count < parameterCount)
            {
                throw new FormatException("Avg function missing operand.");
            }
            AvgFunctionNode node = new AvgFunctionNode();
            for (; parameterCount > 0; parameterCount--)
            {
                node.Parameters.Add(context.PostfixStack.Pop());
            }
            context.PostfixStack.Push(node);
        }

#if DEBUG
        protected override void DumpCore()
        {
            Debug.WriteLine("AvgFunctionNode,children:");
            for (int i = this.Parameters.Count - 1; i >= 0; i--)
            {
                this.Parameters[i].DumpNode();
            }
        }
#endif
    }
}
